package org.jeecg.modules.mes.produce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.client.TransactionClient;
import org.jeecg.modules.mes.produce.entity.MesOnlineMaterieltable;
import org.jeecg.modules.mes.produce.entity.MesOnlineMaterieltableMain;
import org.jeecg.modules.mes.produce.service.IMesOnlineMaterieltableMainService;
import org.jeecg.modules.mes.produce.service.IMesOnlineMaterieltableService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 制造中心-在线料表-主表
 * @Author: jeecg-boot
 * @Date: 2021-05-17
 * @Version: V1.0
 */
@Api(tags = "制造中心-在线料表-主表")
@RestController
@RequestMapping("/produce/mesOnlineMaterieltableMain")
@Slf4j
public class MesOnlineMaterieltableMainController extends JeecgController<MesOnlineMaterieltableMain, IMesOnlineMaterieltableMainService> {

    @Autowired
    private IMesOnlineMaterieltableMainService mesOnlineMaterieltableMainService;

    @Autowired
    private IMesOnlineMaterieltableService mesOnlineMaterieltableService;
    @Autowired
    private TransactionClient transactionClient;


    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param mesOnlineMaterieltableMain
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-主表-分页列表查询")
    @ApiOperation(value = "制造中心-在线料表-主表-分页列表查询", notes = "制造中心-在线料表-主表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesOnlineMaterieltableMain mesOnlineMaterieltableMain,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MesOnlineMaterieltableMain> queryWrapper = QueryGenerator.initQueryWrapper(mesOnlineMaterieltableMain, req.getParameterMap());
        Page<MesOnlineMaterieltableMain> page = new Page<MesOnlineMaterieltableMain>(pageNo, pageSize);
        IPage<MesOnlineMaterieltableMain> pageList = mesOnlineMaterieltableMainService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mesOnlineMaterieltableMain
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-主表-添加")
    @ApiOperation(value = "制造中心-在线料表-主表-添加", notes = "制造中心-在线料表-主表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesOnlineMaterieltableMain mesOnlineMaterieltableMain) {
        return mesOnlineMaterieltableMainService.add(mesOnlineMaterieltableMain);
    }

    /**
     * 编辑
     *
     * @param mesOnlineMaterieltableMain
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-主表-编辑")
    @ApiOperation(value = "制造中心-在线料表-主表-编辑", notes = "制造中心-在线料表-主表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesOnlineMaterieltableMain mesOnlineMaterieltableMain) {
        mesOnlineMaterieltableMainService.updateById(mesOnlineMaterieltableMain);
        QueryWrapper<MesOnlineMaterieltable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("main_id", mesOnlineMaterieltableMain.getId());
        List<MesOnlineMaterieltable> list = mesOnlineMaterieltableService.list(queryWrapper);
        if (list.size() > 0) {
            for (MesOnlineMaterieltable table : list) {
                table.setProductCode(mesOnlineMaterieltableMain.getProductCode());
                table.setProductName(mesOnlineMaterieltableMain.getProductName());
                table.setLineType(mesOnlineMaterieltableMain.getLineType());
                mesOnlineMaterieltableService.updateById(table);
            }
        }
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-主表-通过id删除")
    @ApiOperation(value = "制造中心-在线料表-主表-通过id删除", notes = "制造中心-在线料表-主表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mesOnlineMaterieltableMainService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-主表-批量删除")
    @ApiOperation(value = "制造中心-在线料表-主表-批量删除", notes = "制造中心-在线料表-主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesOnlineMaterieltableMainService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesOnlineMaterieltableMain mesOnlineMaterieltableMain) {
        return super.exportXls(request, mesOnlineMaterieltableMain, MesOnlineMaterieltableMain.class, "制造中心-在线料表-主表");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesOnlineMaterieltableMain.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-制造中心-在线料表-子表-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-子表-通过主表ID查询")
    @ApiOperation(value = "制造中心-在线料表-子表-通过主表ID查询", notes = "制造中心-在线料表-子表-通过主表ID查询")
    @GetMapping(value = "/listMesOnlineMaterieltableByMainId")
    public Result<?> listMesOnlineMaterieltableByMainId(MesOnlineMaterieltable mesOnlineMaterieltable,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        QueryWrapper<MesOnlineMaterieltable> queryWrapper = QueryGenerator.initQueryWrapper(mesOnlineMaterieltable, req.getParameterMap());
        Page<MesOnlineMaterieltable> page = new Page<MesOnlineMaterieltable>(pageNo, pageSize);
        IPage<MesOnlineMaterieltable> pageList = mesOnlineMaterieltableService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mesOnlineMaterieltable
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-子表-添加")
    @ApiOperation(value = "制造中心-在线料表-子表-添加", notes = "制造中心-在线料表-子表-添加")
    @PostMapping(value = "/addMesOnlineMaterieltable")
    public Result<?> addMesOnlineMaterieltable(@RequestBody MesOnlineMaterieltable mesOnlineMaterieltable) {
        if (StringUtils.isBlank(mesOnlineMaterieltable.getMainId())) {
            return Result.error("主表id为空！");
        }
        MesOnlineMaterieltableMain info = mesOnlineMaterieltableMainService.getById(mesOnlineMaterieltable.getMainId());
        if (info == null) {
            return Result.error("主表id有误!未找到该主表信息！");
        }
        mesOnlineMaterieltable.setProductCode(info.getProductCode());
        mesOnlineMaterieltable.setProductName(info.getProductName());
        mesOnlineMaterieltable.setLineType(info.getLineType());
        mesOnlineMaterieltableService.save(mesOnlineMaterieltable);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesOnlineMaterieltable
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-子表-编辑")
    @ApiOperation(value = "制造中心-在线料表-子表-编辑", notes = "制造中心-在线料表-子表-编辑")
    @PutMapping(value = "/editMesOnlineMaterieltable")
    public Result<?> editMesOnlineMaterieltable(@RequestBody MesOnlineMaterieltable mesOnlineMaterieltable) {
        if (StringUtils.isBlank(mesOnlineMaterieltable.getMainId())) {
            return Result.error("主表id为空！");
        }
        MesOnlineMaterieltableMain info = mesOnlineMaterieltableMainService.getById(mesOnlineMaterieltable.getMainId());
        if (info == null) {
            return Result.error("主表id有误!未找到该主表信息！");
        }
        mesOnlineMaterieltable.setProductCode(info.getProductCode());
        mesOnlineMaterieltable.setProductName(info.getProductName());
        mesOnlineMaterieltable.setLineType(info.getLineType());
        mesOnlineMaterieltableService.updateById(mesOnlineMaterieltable);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-子表-通过id删除")
    @ApiOperation(value = "制造中心-在线料表-子表-通过id删除", notes = "制造中心-在线料表-子表-通过id删除")
    @DeleteMapping(value = "/deleteMesOnlineMaterieltable")
    public Result<?> deleteMesOnlineMaterieltable(@RequestParam(name = "id", required = true) String id) {
        mesOnlineMaterieltableService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "制造中心-在线料表-子表-批量删除")
    @ApiOperation(value = "制造中心-在线料表-子表-批量删除", notes = "制造中心-在线料表-子表-批量删除")
    @DeleteMapping(value = "/deleteBatchMesOnlineMaterieltable")
    public Result<?> deleteBatchMesOnlineMaterieltable(@RequestParam(name = "ids", required = true) String ids) {
        this.mesOnlineMaterieltableService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMesOnlineMaterieltable")
    public ModelAndView exportMesOnlineMaterieltable(HttpServletRequest request, MesOnlineMaterieltable mesOnlineMaterieltable) {
        // Step.1 组装查询条件
        QueryWrapper<MesOnlineMaterieltable> queryWrapper = QueryGenerator.initQueryWrapper(mesOnlineMaterieltable, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MesOnlineMaterieltable> pageList = mesOnlineMaterieltableService.list(queryWrapper);
        List<MesOnlineMaterieltable> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "制造中心-在线料表-子表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, MesOnlineMaterieltable.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("制造中心-在线料表-子表报表", "导出人:" + sysUser.getRealname(), "制造中心-在线料表-子表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入  舍弃
     * @return
     */
    /*@RequestMapping(value = "/importMesOnlineMaterieltable/{mainId}")
    public Result<?> importMesOnlineMaterieltable(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<MesOnlineMaterieltable> list = ExcelImportUtil.importExcel(file.getInputStream(), MesOnlineMaterieltable.class, params);
				 for (MesOnlineMaterieltable temp : list) {
                    temp.setMainId(mainId);
					 if( StringUtils.isBlank(temp.getQuery5())){
						 temp.setQuery5("正面");
					 }
					 if(StringUtils.isBlank(temp.getProductCode())||
							 StringUtils.isBlank(temp.getMaterielCode())||
							 StringUtils.isBlank(temp.getPointNum())||
							 StringUtils.isBlank(temp.getLineType())){
						 throw new RuntimeException("成品料号、物料料号、点数、线别等不能为空！");

					 }

					 //根据成品料号去生产订单查询，是否有该生产订单；
					 List<MesOrderProduce> orderProduceList = transactionClient.getOrderProduceList(temp.getProductCode(), temp.getLineType());
					 if (orderProduceList.size()==0){
						 throw new RuntimeException("未找到该成品料号和生产线别的生产订单！");
					 }
				 }
				 long start = System.currentTimeMillis();
				 mesOnlineMaterieltableService.saveBatch(list);
				 //远程调用bom，更新正反面用量
				 for(MesOnlineMaterieltable temp:list){
					 //根据成品料号去生产订单查询，是否有该生产订单；
					 if(StringUtils.isNotBlank(temp.getPointNum())&&!"0".equals(temp.getPointNum().trim())){
						 boolean mark=systemClient.getMCodebomitemForInS(temp.getProductCode(),temp.getMaterielCode(),temp.getQuery5(),temp.getPointNum());
						 if (!mark){
							 throw new RuntimeException("未在bom中找到该成品料号和该物料信息，无法同步正反面用量！");
						 }
					 }
				 }
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }*/

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importMesOnlineMaterieltable/{mainId}")
    public Result<?> importMesOnlineMaterieltable(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        boolean mark = mesOnlineMaterieltableMainService.importMesOnlineMaterieltable(request, response, mainId);
        if (mark) {
            return Result.OK("导入成功！");
        } else {
            return Result.error("导入失败！");
        }
    }

    /*--------------------------------子表处理-制造中心-在线料表-子表-end----------------------------------------------*/


}
